<script type="text/javascript">
	function StudentDispatchCtrl($http, $injector, CtrlUtil, $element, $scope, modalService, $state) {
		var ctrl = this;
		ctrl.memberSize = 30
		ctrl.dispatchedClass = []
		ctrl.rule = 'department'
		ctrl.termChange = function (term) {
			ctrl.term = term
			$http.post(':root/trainee/getDispatchInfo', term).success(function (r) {
				ctrl.dispatch = r;
				ctrl.className = term.name + term.trainType.name;
				if (r.classInfoList.length <= 0) {
					return;
				}
				ctrl.memberSize = r.classInfoList[0].fbbzrs
				ctrl.prefixName = r.classInfoList[0].bjName
				ctrl.prefixName = ctrl.prefixName.substring(0, ctrl.prefixName.length - 2)
				var clazz = ctrl.dispatchedClass = []
				var studentMap = {}
				angular.forEach(r.students, function (v) {
					var arr = studentMap[v[1]] || []
					studentMap[v[1]] = arr
					arr.push(v)
				})
				var list = r.classInfoList.sort(function (a, b) {
					return a.bjCode - b.bjCode;
				})
				angular.forEach(list, function (v, k) {
					clazz[k] = clazz[k] || []
					clazz[k] = clazz[k].concat(studentMap[v.id])
				})
				ctrl.query()
			})
		}
		$scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
			if (ctrl.needSave) {
				event.preventDefault()
				modalService.confirm({
					content: '还有未保存的分配结果,确定不保存直接直接离开吗?'
				}).then(function () {
					ctrl.needSave = false
					$state.go(toState, toParams)
				})
			}
		})
		function dispatch(students, clsNumber) {
			var key = 0, stuMap = {}
			if (ctrl.rule == 'department') {
				key = 3
			} else if (ctrl.rule == 'grade') {
				key = 2
			}
			for (var i = 0; i < students.length; i++) {
				var s = students[i]
				var arr = (stuMap[s[key]] = stuMap[s[key]] || [])
				Math.random() > 0.5 ? arr.unshift(s) : arr.push(s)
			}
			var clazz = []
			var temp = 0;
			angular.forEach(stuMap, function (v) {
				angular.forEach(v, function (s) {
					clazz[temp] = clazz[temp] || []
					clazz[temp].push(s)
					temp++;
					if (temp >= clsNumber) {
						temp = 0
					}
				})
			})
			return clazz;
		}
		this.doDispatch = function () {
			var students = ctrl.dispatch.students
			var stuMap = {}
			ctrl.dispatchedClass = []
			angular.forEach(students, function (s) {
				if (s[5]) {
					return;
				}
				var arr = (stuMap[s[4]] = stuMap[s[4]] || [])
				arr.push(s)
			})
			var message = '分配完成'
			angular.forEach(stuMap, function (v, k) {
				var clsNumber = Math.floor(v.length / ctrl.memberSize)
				var xqbj = dispatch(v, clsNumber)
				message += (',' + xqbj.length + '个班级')
				ctrl.dispatchedClass = ctrl.dispatchedClass.concat(xqbj)
			})
			ctrl.prefixName = ctrl.className
			ctrl.query()
			ctrl.needSave = true
			modalService.succ(message)
		}
		this.query = function () {
			ctrl.pageNumber = ctrl.pageNumber || 0
			ctrl.pageSize = 15
			ctrl.entities = {}
			ctrl.entities.content = ctrl.dispatchedClass.slice(ctrl.pageNumber * ctrl.pageSize, (ctrl.pageNumber + 1) * ctrl.pageSize)
			ctrl.entities.totalElements = ctrl.dispatchedClass.length
			ctrl.entities.totalPages = Math.ceil(ctrl.entities.totalElements / ctrl.pageSize)
		}

		this.viewDetail = function (c) {
			var ids = []
			angular.forEach(c, function (v) {
				ids.push(v[0])
			})
			$http.post(':root/trainee/findAllByIds', {
				ids: ids
			}).success(function (r) {
				var content = $element.find('[template]>[detail]').clone()
				modalService.show({
					title: '班级详细信息',
					content: content,
					size: 'lg',
					result: r,
					ctrl: ctrl
				}).then(function (r) {
				})
			})
		}
		this.save = function () {
			if (ctrl.dispatchedClass.length == 0) {
				modalService.error('请先进行分配操作', 1500)
				return;
			}
			var s = []
			angular.forEach(ctrl.dispatchedClass, function (v) {
				s.push(v)
			})
			var form = {
				claaName: ctrl.prefixName,
				memberSize: ctrl.memberSize,
				students: JSON.stringify(s),
				term: ctrl.dispatch.currentTerm
			}
			$http.post(':root/trainee/dispatch', form).success(function (r) {
				modalService.succ('保存成功', 1500)

			})['finally'](function () {
				ctrl.needSave = false
			})
		}
		ctrl.backToQuery = function () {
			if (ctrl.needSave) {
				event.preventDefault()
				modalService.confirm({
					content: '还有未保存的分配结果,确定不保存直接直接离开吗?'
				}).then(function () {
					ctrl.needSave = false
					$scope.mainCtrl.toQuery()
				})
			} else {
				$scope.mainCtrl.toQuery()
			}
		}
	}

</script>
<div class=" " ng-controller="StudentDispatchCtrl as ctrl" ng-init="ctrl.query()">
	<div class="panel panel-cys">
		<div class="panel-heading">
			<h3 class="panel-title">
				<span class="glyphicon glyphicon-fullscreen"></span> 分班管理
				<small class="pull-right">【分配状态】：{{(ctrl.dispatch.allStudentCount-ctrl.dispatch.dispatchedCount)>0?'未分配完成':'分配完成'}}</small>
			</h3>
		</div>
		<div class="panel-body">
			<form class="form-horizontal">
				<div class="form-group">
					<label class="col-md-3 control-label">期次</label>
					<div class="col-md-8">
						<data entity="Term" auto-load="true" after-refresh="terms=data;ctrl.termChange(data[0])">
							<filter field="status" value="1"></filter>
						</data>
						<select class="form-control" ng-change="ctrl.termChange(ctrl.term)" chosen ng-options="m as (m.name+m.trainType.name) for m in terms" ng-model="ctrl.term">
						  <option value="">期次</option>
						</select>
					</div>
				</div>
				<div class="form-group">
					<label class="col-md-3 control-label">当前分配情况</label>
					<div class="col-md-8">
						<div class="form-control-static">
							学生生总人数：
							<label>{{ctrl.dispatch.allStudentCount}}</label> 已分配人数：
							<label>{{ctrl.dispatch.dispatchedCount}}</label> 班级数量：
							<label>{{ctrl.dispatch.classInfoList.length||0}}</label> 班级人数标准：
							<label>{{ctrl.dispatch.classInfoList[0].fbbzrs}}</label>
						</div>
					</div>
				</div>
				<div class="form-group">
					<label class="col-md-3 control-label">设置班级人数标准</label>
					<div class="col-md-3">
						<input type="number" class="form-control" ng-model="ctrl.memberSize">
					</div>
					<label class="col-md-3 control-label">班级名称</label>
					<div class="col-md-3">
						<input type="text" class="form-control" placeholder="从数字1开始递增" ng-model="ctrl.className">
					</div>
				</div>
				<div class="form-group">
					<label class="col-md-3 control-label">设置分配规则</label>
					<div class="col-md-8">
						<div class="radio">
							<label>
								<input type="radio" ng-model="ctrl.rule" value="department" name="optionsRadios">
								随机分配，优先保证同一院系的学生不在一个班级，多余人员平均分配
							</label>
						</div>
						<div class="radio">
							<label>
								<input type="radio" ng-model="ctrl.rule" value="grade" name="optionsRadios">
								随机分配，优先保证同一年级的学生不在一个班级，多余人员平均分配
							</label>
						</div>
						<div class="radio">
							<label>
								<input type="radio" ng-model="ctrl.rule" value="random" name="optionsRadios">
								随机分配
							</label>
						</div>
					</div>
				</div>
				<div class="row pull-right">
					<div class="col-md-12">
						<a class="btn btn-cys btn-sm" ng-click="ctrl.backToQuery()">
							<span class="glyphicon glyphicon-arrow-left"></span>
							返回查询
						</a>
						<a class="btn btn-cys btn-sm" ng-click="ctrl.doDispatch()">
							<span class="glyphicon glyphicon-refresh"></span>
							{{ctrl.dispatch.dispatchedCount>0?'重新分配':'分配'}}
						</a>
					</div>
				</div>
			</form>
		</div>
	</div>
	<!-- data grid area -->
	<div class="panel panel-cys">
		<div class="panel-heading">
			<h3 class="panel-title">
				<span class="glyphicon glyphicon-th-list"></span> 分配结果
			</h3>
		</div>
		<div class="container-fluid" style="padding-bottom: 10px; padding-top: 10px;">
			<button ng-disabled="!ctrl.needSave" ng-click="ctrl.save()" class="btn btn-danger">保存</button>
			<div class="pull-right" ng-include="':root/components/page.html'"></div>
		</div>
		<div class="container-fluid">
			<table class="table table-bordered table-hover table-striped">
				<tr>
					<th>班级号</th>
					<th>班级名称</th>
					<th>班级人数</th>
					<th>班级人数-标准人数</th>
					<th>操作</th>
				</tr>
				<tr ng-repeat="c in ctrl.entities.content">
					<td>{{$index+1+(ctrl.pageNumber*ctrl.pageSize)}}</td>
					<td>{{ctrl.prefixName+($index+1+(ctrl.pageNumber*ctrl.pageSize))}}班</td>
					<td>{{c.length}}</td>
					<td>{{ctrl.memberSize}}</td>
					<td><a href="javascript:;" ng-click="ctrl.viewDetail(c)">查看</a> <a href="javascript:;">导出名单</a></td>
				</tr>
			</table>
			<p>
				共有记录：
				<span>{{ctrl.entities.totalElements}}</span> 条
			</p>
		</div>
		<!-- data grid area END -->
	</div>
	<div template ng-non-bindable class="hidden">
		<table class="table table-bordered table-hover table-striped" detail>
			<tr>
				<th>姓名</th>
				<th>性别</th>
				<th>学号</th>
				<th>年级</th>
				<th>院系</th>
				<th>学生类别</th>
				<th>联系电话</th>
				<th>校区</th>
				<th>职务</th>
			</tr>
			<tr ng-repeat="s in result">
				<td>{{s.user.name}}</td>
				<td>{{s.sexString}}</td>
				<td>{{s.user.uid}}</td>
				<td>{{s.user.grade}}</td>
				<td>{{$root.departmentMap[s.user.department].name}}</td>
				<td>{{s.user.type}}</td>
				<td>{{s.phone}}</td>
				<td>{{s.xq}}</td>
				<td>{{s.zw}}</td>
			</tr>
		</table>
	</div>
	<!-- main area END-->
</div>